package cn.cd.anStudio;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import cn.cd.anStudio.CommonUtil.AnstudioSynDialog;
import cn.cd.anStudio.util.MyBusCommonUtil;
import cn.cd.anStudio.util.MyBusPropertySQLHelper;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.widget.ProgressBar;

public class MyBusActivity extends Activity {
	
	private static final String TAG = "MyBusActivity";
	
	//TODO : Add more valid check here
	private final int LAUNCH_CHECK_ANNOUNCE_READY = 0;
	private final int LAUNCH_CHECK_NETWORK_READY  = 1;
	private final int LAUNCH_CHECK_SERVER_READY   = 2;
	private final int LAUNCH_CHECK_LOCAL_READY    = 3;
	
	public ProgressBar loginProBar = null;
	private MyBusPropertySQLHelper tmpSQLite = new MyBusPropertySQLHelper(this);

	private void iniApplicationVersion() {
		Cursor myCur = tmpSQLite.select();
        int propertyIndex = myCur.getColumnIndex(MyBusPropertySQLHelper.MYBUS_PROPERTY_DB_PROPERTY_NAME_KEY);
        int valueIndex = myCur.getColumnIndex(MyBusPropertySQLHelper.MYBUS_PROPERTY_DB_PROPERTY_VALUE_KEY);

        if (myCur != null) {
        	if (myCur.moveToFirst()) {
        		do {
        			if (myCur.getString(propertyIndex).equals(MyBusPropertySQLHelper.MYBUS_PROPERTY_DB_VERSION_NAME)) {
        				MyBusCommonBase.setVersion(myCur.getString(valueIndex));
        			}
        		}
        		while (myCur.moveToNext());
        	}
        	
        	myCur.close();
        }
	}
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        if (MyBusCommonBase.DEBUG) {
        	Log.v(TAG, "Activity Created");
        }
        
        iniApplicationVersion();

        loginProBar = (ProgressBar) findViewById(R.id.loginProBar);
        
        if (null == loginProBar) {
        	if (MyBusCommonBase.DEBUG) {
        		Log.v(TAG, "Unable to create progress bar, exit here");
        	}
        	finish();
        }
        
        logCheck(LAUNCH_CHECK_ANNOUNCE_READY);
    }
	
	Handler loginHandler = new Handler() {
		
		public void handleMessage(Message msg) {
			
			if (MyBusCommonBase.MY_BUS_FAILED == msg.arg2) {
				if (MyBusCommonBase.DEBUG) {
					Log.v(TAG, "Error found at pre-check");
				}
				errorWithLog(msg.arg1);
				return;
			}
			
			//Set the progress bar according to the check result
			switch(msg.arg1) {
			case LAUNCH_CHECK_ANNOUNCE_READY:
				if (MyBusCommonBase.DEBUG) {
					Log.v(TAG, "Announce check pass!");
				}
				loginProBar.setProgress(20);
				logCheck(msg.arg1 + 1);
				break;
			case LAUNCH_CHECK_NETWORK_READY:
				if (MyBusCommonBase.DEBUG) {
					Log.v(TAG, "Network check pass!");
				}
				loginProBar.setProgress(40);
				logCheck(msg.arg1 + 1);
				break;
			case LAUNCH_CHECK_SERVER_READY:
				if (MyBusCommonBase.DEBUG) {
					Log.v(TAG, "Server check pass!");
				}
				loginProBar.setProgress(60);
				logCheck(msg.arg1 + 1);
				break;
			case LAUNCH_CHECK_LOCAL_READY:
				if (MyBusCommonBase.DEBUG)
					Log.v(TAG, "Local resource check pass!");
				
				loginProBar.setProgress(100);
				
				if (MyBusCommonBase.DEBUG)
					Log.v(TAG, "All pre-check pass, load application");
				Intent iIntent = new Intent();
				iIntent.setAction("com.cn.cd.anstudio.action.MYBUSLOCATION");
				startActivity(iIntent);
				finish();
				break;
			default:
			}
		}
	};
    
    public void logCheck(int partId) {
    	Message checkMsg = new Message();
    	checkMsg.arg1 = partId;
    	checkMsg.arg2 = MyBusCommonBase.MY_BUS_OK;
    	switch (partId) {
    	case LAUNCH_CHECK_ANNOUNCE_READY:
    		if (MyBusCommonUtil.isFirstLogin()) {
	    		AnstudioSynDialog myBusLaunchCheckBox =
	    		        new AnstudioSynDialog(
	    		        		  this
	    		        		, getResources().getString(R.string.my_bus_announce)
	    		        		, getResources().getString(R.string.common_continue)
	    		        		, getResources().getString(R.string.common_exit));
	    		
	    		myBusLaunchCheckBox.showDialog();
	    		myBusLaunchCheckBox.setTitle(getResources().getString(R.string.my_bus_announce_title));
	    		
	    	    if (DialogInterface.BUTTON2 == myBusLaunchCheckBox.getDialogResult()) {
	    	    	finish();
	    	    	return;
	    	    } else {
	    	    	tmpSQLite.insert(MyBusPropertySQLHelper.MYBUS_PROPERTY_DB_VERSION_NAME
	    	    			, "1.0");
	    	    }
    		}
    		break;
    	case LAUNCH_CHECK_NETWORK_READY:
    		if (!isNetworkReady()) {
    			checkMsg.arg2 = MyBusCommonBase.MY_BUS_FAILED;
    		}
			break;
		case LAUNCH_CHECK_SERVER_READY:
			if (!isServerReady()) {
    			checkMsg.arg2 = MyBusCommonBase.MY_BUS_FAILED;
    		}
			break;
		case LAUNCH_CHECK_LOCAL_READY:
			break;
		default:
    	}
    	
    	loginHandler.sendMessage(checkMsg);
    }
    
    public void errorWithLog(int errorMod) {
    	
    	String errInfo;
    	boolean isNeedService = false;
    	
    	OnClickListener errDialogListener = new OnClickListener() {
			public void onClick(DialogInterface arg0, int arg1) {

				switch(arg1) {
				case AlertDialog.BUTTON2:
					startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
					//Fall through
				case AlertDialog.BUTTON1:
					finish();
					break;
				}
			}
    	};
    	
    	switch(errorMod) {
    	case LAUNCH_CHECK_NETWORK_READY:
			errInfo = getResources().getString(R.string.login_net_error);
			isNeedService = true;
			break;
		case LAUNCH_CHECK_SERVER_READY:
			errInfo = getResources().getString(R.string.login_server_error);
			break;
		case LAUNCH_CHECK_LOCAL_READY:
			errInfo = getResources().getString(R.string.login_local_error);
			break;
		default:
			errInfo = getResources().getString(R.string.login_unkown_error);
    	}

    	AlertDialog errDialog = new AlertDialog.Builder(this).create();
    	errDialog.setMessage(errInfo);
		errDialog.setButton(getResources().getString(R.string.common_ok), errDialogListener);
		
		if (isNeedService) {
			errDialog.setButton2(getResources().getString(R.string.common_setting), errDialogListener);
		}

		errDialog.show();
    }
    
    private boolean isNetworkReady() {
    	boolean ret = false;
    	
    	if (MyBusCommonBase.DEBUG)
    		Log.v(TAG, "Check for network status");
    	
    	// Check network status
    	ConnectivityManager cm =
    			(ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
    	if (null != cm.getActiveNetworkInfo()) {
    		
    		if (MyBusCommonBase.DEBUG)
    			Log.v(TAG, "Network is ready this moment");
    		ret = true;
    	}
    	         
    	return ret;
    }
    
    private boolean isServerReady() {
    	boolean ret = false;
    	
    	if (MyBusCommonBase.DEBUG)
    		Log.v(TAG, "Check for server status");
    	
    	try {
            URL serverUrl = new URL(MyBusCommonBase.SERVER);
            HttpURLConnection urlc = (HttpURLConnection) serverUrl.openConnection();

            //TODO : Set the connect time out maybe much better
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
            	if (MyBusCommonBase.DEBUG)
            		Log.v(TAG, "Server is ready");
                ret = true;
            }
            
            urlc.disconnect();
        } catch (MalformedURLException e1) {
        	if (MyBusCommonBase.DEBUG)
        		Log.v(TAG, "Server URL is incorrect");
        } catch (IOException e) {
        	if (MyBusCommonBase.DEBUG)
        		Log.v(TAG, "Failed to connect to server");
        }
    	
    	return ret;
    }
}
